from flask import request
from web.control.error.error_code import ParameterException, SQLMissException, SQLException
from web.model.base_model import db


def get_json():
    """
    获取请求中json类型的数据

    :return: 获取到的json数据
    """
    try:
        data = request.json
    except Exception as error:
        raise ParameterException(msg=error)
    return data


def get_args(key):
    """
    获取请求中的参数信息

    :param key: 待获取的数据的key
    :type key: str
    :return:
    """
    try:
        value = request.args.get(key)
    except Exception as error:
        raise ParameterException(msg=error)
    return value


def assignment(cls, clsForm, json):
    """
    对获取到的数据进行验证

    :param cls: 要赋值的模型类
    :param clsForm:  校验的模型类
    :param json: 要校验的数据
    :type cls: class
    :type clsForm: class
    :type json : dict
    :return: 若没错则返回赋值后的模型类实例，有异常则抛出异常
    """
    form = clsForm(data=json)
    form.validate_error_message()
    class_ = cls()
    class_.set_attrs(form.data)
    return class_


def query_by_id(cls, id):
    """
    使用主键查询表数据

    :param cls: 要赋值的模型类
    :param id: 数据的主键
    :type cls: class
    :type id: str
    :return: 成功则返回查询到的数据集合，出现异常则抛出异常
    """
    try:
        data = cls.query.filter(cls.id == id).first()
    except Exception as e:
        raise SQLMissException(msg="数据查询失败")
    if data:
        return data
    else:
        raise SQLMissException(msg="没有查询到有效数据")


def commit_option(cls, id):
    """
    提交选项数据，每调用该函数一次表示该选项被用户选择一次

    :param cls: 要赋值的模型类
    :param id: 数据的主键
    :return:
    """
    try:
        option = cls.query.filter(cls.id == id).first()
        option.count += 1
    except Exception as error:
        raise SQLMissException(msg="数据库查询不到响应数据")
    try:
        db.session.commit()
    except Exception as error:
        raise SQLException(msg='数据提交失败')
